
Ext.define('Sencha.controller.DictionarySourceController', {
    extend: 'Ext.app.Controller',

    config: {
        // Flags used to check state of search filter buttons
        engDictionaryButtonOn: true,
        iwaDictionaryButtonOn: true,
           
        lastSearchString: '',
           
        mediaPtr: null,
                
        // Dictionary Target & Source property
        sourceWordfield : "",
        partOfSpeechField : "",
        inflectionField : "",
        disambiguationField : "",
        targetWordField : "",
        detailedEntryField : "",
        noteField : "",
        //metadata form
        currentDate: "",
        //currentTime: "",
        currentLatitude: "",
        currentLongitude: "",
        recordingDevice: "",
        //speaker form
        speakerName: "",
        speakerDOB: "",
        speakerGender: "",
        speakerComment: "",
        //collector form
        collectorName: "",
        collectorDOB: "",
        collectorGender: "",
        collectorComment: "",
        
        //id collection
        targetId: "",
        collectorId: "",
        speakerId: "",
        
        refs: {
           tabPanel: 'tabview',
           main: 'dictionarysourcenavigationview',
           dictionarySourceListView: 'dictionarysourcelistview',
           dictionaryEntryButton: 'button[id=dictionaryEntryButton]',

           dictionaryDeleteButton: 'button[id=deleteDictionaryButton]',
           //editDictionaryButton: 'button[cls=editDictionaryButton]',
           dictionarySearchField: 'searchfield[name=dictionarySearchField]',
           //dictionarySourceListView: 'dictionarysourcelistview',
           
           dictionaryDetailView: 'dictionarytargetdetailview',
           
           //engDictionaryButton: 'button[text="ENG"]',

           engDictionaryButton: 'button[id=engDictionaryButtonId]',
           iwaDictionaryButton: 'button[id=iwaDictionaryButtonId]',

            
            
           addImageButtonRef: 'button[cls=addImageButtonCls]',
           audioRecordButtonRef: 'button[cls=audioRecordButtonCls]',
           
           dictionaryForm: 'fieldset[id="dicFormFieldSet"]',
           dicMetadaForm: 'fieldset[id="dicMetadataFieldset"]',
           
           //speaker
           
           speakerNameField: 'fieldset[id="speakerNameFieldset"]',
           speakerGenderField: 'radiofield[name="speakerGender"]',
           speakerCommentField: 'fieldset[id="speakerCommentFieldset"]',
           
           
           //collector
           
           collectorNameField: 'fieldset[id="collectorNameFieldset"]',
           collectorGenderField: 'radiofield[name="collectorGender"]',
           collectorCommentField: 'fieldset[id="collectorCommentFieldset"]',
           
      

        },
        
     
        control: {
            'main': {
                initialize: 'onInit'
            },
            'dictionarySourceListView': {
                disclose: 'showDetail',
                itemtap: 'playAudio'
            },
            'dictionaryEntryButton':{        
                tap:'onDictionaryEntryButtonTap'
            },
            'dictionarySearchField':{        
                keyup:'filterDictionarySearch',
                clearicontap:'clearDictionarySearchFilter'
            },
            'engDictionaryButton' :{
           		tap: 'toggleEngDictionaryButton',
                show: 'showDictionaryAddButton'
            },
            'iwaDictionaryButton' :{
           		tap: 'toggleIwaDictionaryButton'
            },
            'dictionarysourcenavigationview':{
            	back:'onBackButton'
           },
           'addImageButtonRef':{
                tap:'onAddImageTap'
           },
           'audioRecordButtonRef':{
                tap:'onAudioRecordTap'

           },
           'button[id="dicMetadataButton"]':{
           		tap:'showMetadataForm'
           },
           'button[id="collectorButton"]':{
           		tap:'showCollectorForm'
           },
           'button[id="speakerButton"]':{
           		tap:'showSpeakerForm'
           },
           'button[id="deleteDictionaryButton"]':{
           		tap:'deleteDictionaryEntry'
           }/*,
           'image[cls="jumpToWordmakerButton"]':{
                tap:'onJumpToWordMaker'
           }
            */
        }
    },
        
    // Jump to Wordmaker with this word selected
    //
    /*
    onJumpToWordMaker: function() {
        // Set stem
        // ...
        this.getTabPanel().setActiveItem(2);   
    },
    */

    onInit: function() {
        console.log(' in on init...');
        this.filterDictionarySearch();
    },
    
    tapDelegate: function() {
        console.log('delegate tap handler');
    },
    
    /*
    onDetailViewShow: function() {
        console.log("detail view ready");
           var currentObj = this;
           
        var el = Ext.get("detailView");
        el.on('swipe', function(event) {
            //alert(event.direction);
              currentObj.getMain().push({
                                  xtype: 'dictionarytargetdetailview',
                                        id: 'detailView2'
                                  
                                  });
            
        });
    },
    */       
           
    // Handle navigation bar button taps ie. add new dict. entry, edit dict. entry, done (eidting, adding)
    onDictionaryEntryButtonTap: function() {
        var innerItems = this.getMain().getInnerItems();
        var currentItem = innerItems[innerItems.length-1].xtype; // get current screen/component
        
        switch(currentItem)
        {
            // if this is the dictionary list view then add entry
            case "dictionarycontainerlist":
                console.log("add dict entry");
                this.getDictionaryEntryButton().setText('DONE');
                this.showForm();
                break;
            // if this is the dictionary detail view then edit entry
            case "dictionarytargetdetailview":
                console.log("edit dict entry");
                this.getDictionaryEntryButton().setText('DONE');
                this.editForm();
                break;
            case "dicmetadataformview":
            	//saving data on metadata form
            	
            	this.setCurrentDate(this.getDicMetadaForm().getComponent('dateField').getValue());
            	this.setCurrentLatitude(this.getDicMetadaForm().getComponent('latitudeField').getValue());
            	this.setCurrentLongitude(this.getDicMetadaForm().getComponent('longitudeField').getValue());
            	this.setRecordingDevice(this.getDicMetadaForm().getComponent('recordingDeviceField').getValue());            	
            	
            	this.getDictionaryEntryButton().setText('DONE');
            	this.getMain().pop();
            	
                	
            	
            	break;
            	
            case "speakerformview":

            	this.setSpeakerName(this.getSpeakerNameField().getComponent('speakerNameField').getValue());
            	
            	this.setSpeakerDOB(this.getSpeakerNameField().getComponent('speakerDOBField').getFormattedValue());
            	    	
            	this.setSpeakerGender(this.getSpeakerGenderField().getGroupValue());
        	
            	this.setSpeakerComment(this.getSpeakerCommentField().getComponent('speakerCommentField').getValue());
            
            	this.getMain().pop();
            	break;
            	
            case "collectorformview":
            	this.setCollectorName(this.getCollectorNameField().getComponent('collectorNameField').getValue());
            	
            	this.setCollectorDOB(this.getCollectorNameField().getComponent('collectorDOBField').getFormattedValue());
            	
            	this.setCollectorGender(this.getCollectorGenderField().getGroupValue());
            	
            	this.setCollectorComment(this.getCollectorCommentField().getComponent('collectorCommentField').getValue());
            	            	
            	this.getMain().pop();
            	
            	break;
            	
            // if this is the dictionary detail view then edit entry
            case "dictionaryformview":
                var previousItem = innerItems[innerItems.length-2].xtype;
                
                // if add dictionary entry
                if (previousItem=="dictionarycontainerlist") {
                    // Save new entry
                    console.log("save new dict entry");
           
                    // call fn to save new entry
                    this.saveForm();
           
                    // Refresh list to show new item
                    this.filterDictionarySearch();
           
                    this.getDictionaryEntryButton().setText('+');
                    
                    this.getMain().pop();
                } 
                // if edit dictionary entry
                else {
                    // Save existing entry
                    console.log("save existing dict entry");
                    
                    // call fn to save existing entry
                    // ...
                    
                    this.updateForm();
                    
                    // Refresh list to show new item
                    this.filterDictionarySearch();
                    // Refresh this detail page in carousel
                    
           
                    this.getDictionaryEntryButton().setText('EDIT');
           
                    this.getMain().pop(2); // pop 2 to return us to list, otherwise page in carousel is out of date
                }
                break;
        }
    },
    
    //fired when back button is pressed on dictionary 
    //
    onBackButton: function(){
        var innerItems = this.getMain().getInnerItems();
        var currentItem = innerItems[innerItems.length-2].xtype; // get screen/component we came from
		
        // This code when using string comparison slows the back buttons respone time by about a second!!!
        // Not usre this will work once we start using the other tabs ie. onBackButton will capture
        // all back button events probably?
        switch(currentItem)
        {
            // if the the list view
            case "dictionarycontainerlist":
           console.log('case dictionarycontainerlist');
                this.getDictionaryEntryButton().show();
                this.getDictionaryEntryButton().setText('+');
                //this.getDictionaryEntryButton().setIcon('images/engDictButton@2x.png');
                break;
            // if the detail view
            case "dictionarytargetdetailview":
           console.log('case dictionarytargetdetailsview');
                //  this.getDictionaryEntryButton().setIcon('');
                //this.getDictionaryEntryButton().show();
                this.getMain().getLayout().setAnimation('slide');
                this.getDictionaryEntryButton().setText('EDIT');
                break;
            // ...
            case "dictionaryformview":
            	this.getDictionaryEntryButton().setText('DONE');
                break;
            // if the image view close up
            case "imageview":
                console.log('case imageview');
                //this.getMain().getLayout().setAnimation('slide');
                break;
        }
    },
    
    //show detail view for specific dictionary source word
    //
    showDetail: function(list, record, target, index, theEvent) {
        theEvent.stopPropagation(); // need to stop event bubbling up, otherwise ontap event is fired too
           
        // Sencha bug allows the disclosure arrow to be clicked more than once, so check for this
        var innerItems = this.getMain().getInnerItems();
        if ( innerItems.length > 1 ) {
           return;
        } 
        
        this.getDictionaryEntryButton().setText('EDIT');
        
           
           console.log('random dictionarySources tgtword =' + Ext.getStore("DictionaryTargets").getById('20').get('targetWord') );
           
           console.log('count = ' + Ext.getStore("DictionaryTargets").getCount() );
        // Get associated DictionaryTarget record using dictionaryTargetId foreign key
           var dictionaryTargetId = record.get('dictionaryTargetId');
           console.log('dictionaryTargetId = ' + dictionaryTargetId);
        var associatedRecord = Ext.getStore("DictionaryTargets").getById( dictionaryTargetId );
        //var associatedRecord = Ext.getStore("DictionaryTargets").getAt( 8 );
        if (associatedRecord) {
           console.log('associatedRecord not null');
           console.log('associated target word=' + associatedRecord.get('targetWord') );
        } else {
           console.log('associatedRecord is null');
        }
           
        this.getMain().push({
            xtype: 'dictionarytargetdetailview',
            dictionarySourceId: record.get('id'),
            listView: list,
            selectedItem: index,
        });
                            
        if( record.get('isEditable') == "false"){
           this.getDictionaryEntryButton().hide();
	    }        
    },
    
    //show add form for dictionary
    //
   	showForm : function(){
        // clear it
        this.setSourceWordfield("");
        this.setPartOfSpeechField("");
        this.setInflectionField("");
        this.setDisambiguationField("");
        this.setTargetWordField("");
        this.setDetailedEntryField("");
        this.setNoteField("");
        
        this.setTargetId("");
           
        //metadata form
		//Getting the current date, time
    	var d = new Date();
        this.setCurrentDate( d.getTime() );
        
        /*
    	var curr_date = d.getDate();
    	var curr_month = d.getMonth() + 1; //months are zero based
    	var curr_year = d.getFullYear();
    
    	curr_full_date = curr_date + "/" + curr_month + "/" + curr_year;
    	
    	var curr_hour = d.getHours();
    	var curr_min = d.getMinutes();
    	var curr_sec = d.getSeconds();
    	
    	curr_full_time = curr_hour + ":" + curr_min + ":" + curr_sec;
    	
    	var deviceName = device.name;
        
        this.setCurrentDate(curr_full_date);
        */
       
           
        // Set location
        var thisPtr = this;
        navigator.geolocation.getCurrentPosition(
            // Success callback
            function(position) {
                thisPtr.setCurrentLatitude( position.coords.latitude );
                thisPtr.setCurrentLongitude( position.coords.longitude ); 
            }, 
            // Error callback
            function(error) {
                console.log('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
                thisPtr.setCurrentLatitude('');
                thisPtr.setCurrentLongitude('');
            }
        );
        
        this.setRecordingDevice( device.name );
           
        //speaker form
        this.setSpeakerName("");
        this.setSpeakerDOB("");
        this.setSpeakerGender("");
        this.setSpeakerComment("");
        
        //collector form
        this.setCollectorName("");
        this.setCollectorDOB("");
        this.setCollectorGender("");
        this.setCollectorComment("");
   
    	this.getMain().push({
    		xtype: 'dictionaryformview'			                    
        });
        
        this.getDictionaryDeleteButton().hide();
   	},
   	
    // Delete dictionary entry
    //
   	deleteDictionaryEntry : function(){
		var dictionarySourceStore = Ext.getStore("DictionarySources");
		var dictionaryTargetStore = Ext.getStore("DictionaryTargets");
		var speakerStore = Ext.getStore("Speakers");
		var collectorStore = Ext.getStore("Collectors");
		
		var sourceModel = dictionarySourceStore.getById(this.getDictionaryForm().getComponent('sourceIdField').getValue());
	   	
	   	dictionarySourceStore.remove(sourceModel);
	   	dictionarySourceStore.sync();

		var dicTargetId = this.getDictionaryForm().getComponent('targetIdField').getValue();
	 	
	   	if( dictionarySourceStore.find("dictionaryTargetId", dicTargetId) == -1){
	   		var targetModel = dictionaryTargetStore.getById(dicTargetId);
	   		
	   		dictionaryTargetStore.remove(targetModel);
	   		dictionaryTargetStore.sync();
	   		
	   		var dicSpeakerId = this.getDictionaryForm().getComponent('speakerIdField').getValue();
	   		var dicCollectorId = this.getDictionaryForm().getComponent('collectorIdField').getValue();
	   		
	   		if(dictionaryTargetStore.find("speakerId", dicSpeakerId) == -1){
	   			var speakerModel = speakerStore.getById(dicSpeakerId);
	   			
	   			speakerStore.remove(speakerModel);
	   			speakerStore.sync();
	   		}
	   		
	   		if(dictionaryTargetStore.find("collectorId", dicCollectorId) == -1){
	   			var collectorModel = collectorStore.getById(dicCollectorId);
	   			
	   			collectorStore.remove(collectorModel);
	   			collectorStore.sync();
	   		}
	   		
	   	}
	   	
   		this.getDictionaryEntryButton().setText('+');
   		this.getMain().pop(2);
   		//this.getMain().pop();
   		//this.getMain().pop();	
   	},
      
           
    // Edit form
    //
   	editForm : function(){
   		console.log("editForm...");   
        var curRecord = this.getDictionaryDetailView().getListView().getStore().getAt( this.getDictionaryDetailView().getCurrentListItem() );
           console.log('curRecord.get(sourceWord) = ' + curRecord.get('sourceWord') );
        /*   
   		var innerItems = this.getMain().getInnerItems();
   		var currentItem = innerItems[innerItems.length-1]; // get screen/component we came from
   		
   		var dictionaryTargetId = currentItem.getData()['dictionaryTargetId'];
   		var dictionarySourceId = currentItem.getData()['dictionarySourceId'];
   		*/
           
        var dictionaryTargetId = curRecord.get('dictionaryTargetId');
        var dictionarySourceId = curRecord.get('id');
           
   		var dictionaryTargetStore = Ext.getStore("DictionaryTargets").getById(dictionaryTargetId);
   		var dictionarySourceStore = Ext.getStore("DictionarySources").getById(dictionarySourceId);

   		var collectorStore = Ext.getStore("Collectors").getById(dictionaryTargetStore.get('collectorId'));
   		var speakerStore = Ext.getStore("Speakers").getById(dictionaryTargetStore.get('speakerId'));
   		

   		this.getMain().push({
   			xtype: 'dictionaryformview'			                    
   		});
   		   		   	
   		this.getDictionaryForm().getComponent('sourceWordField').setValue(dictionarySourceStore.get('sourceWord'));
   		this.getDictionaryForm().getComponent('partOfSpeechField').setValue(dictionarySourceStore.get('partOfSpeech'));
   		this.getDictionaryForm().getComponent('inflectionField').setValue(dictionarySourceStore.get('inflection'));
   		this.getDictionaryForm().getComponent('disambiguationField').setValue(dictionarySourceStore.get('disambiguation'));
   		this.getDictionaryForm().getComponent('targetWordField').setValue(dictionarySourceStore.get('targetWord'));
   		this.getDictionaryForm().getComponent('detailedEntryField').setValue(dictionaryTargetStore.get('detailedEntry'));
   		this.getDictionaryForm().getComponent('noteField').setValue(dictionaryTargetStore.get('note'));
   		
   		this.getDictionaryForm().getComponent('targetIdField').setValue(dictionaryTargetId);
   		this.getDictionaryForm().getComponent('sourceIdField').setValue(dictionarySourceId);
   		this.getDictionaryForm().getComponent('speakerIdField').setValue(dictionaryTargetStore.get('speakerId'));
   		this.getDictionaryForm().getComponent('collectorIdField').setValue(dictionaryTargetStore.get('collectorId'));
   	
	
   		//setting the metadata, speaker, and collector
   		//Getting the current date and time
   		var d = new Date();
        this.setCurrentDate( d.getTime() );
           
        /*
   		var curr_date = d.getDate();
   		var curr_month = d.getMonth() + 1; //months are zero based
   		var curr_year = d.getFullYear();
   	
   		curr_full_date = curr_date + "/" + curr_month + "/" + curr_year;
   		
   		var curr_hour = d.getHours();
   		var curr_min = d.getMinutes();
   		var curr_sec = d.getSeconds();
   		
   		curr_full_time = curr_hour + ":" + curr_min + ":" + curr_sec;
   		
   		var deviceName = device.name;
   	    
   	    this.setCurrentDate(curr_full_date);
        */
           
        var thisPtr = this;
        navigator.geolocation.getCurrentPosition(
            // Success callback
            function(position) {
                thisPtr.setCurrentLatitude( position.coords.latitude );
                thisPtr.setCurrentLongitude( position.coords.longitude ); 
            }, 
            // Error callback
            function(error) {
                console.log('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
                thisPtr.setCurrentLatitude('');
                thisPtr.setCurrentLongitude('');
            }
        );
           
        this.setRecordingDevice( device.name );
   	    
   	    //speaker form
   	    this.setSpeakerName(speakerStore.get('name'));
   	    this.setSpeakerDOB(speakerStore.get('birthDate'));
   	    this.setSpeakerGender(speakerStore.get('gender'));
   	    this.setSpeakerComment(speakerStore.get('comments'));
   	    
   	    //collector form
   	    this.setCollectorName(collectorStore.get('name'));
   	    this.setCollectorDOB(collectorStore.get('birthDate'));
   	    this.setCollectorGender(collectorStore.get('gender'));
   	    this.setCollectorComment(collectorStore.get('comments'));
   	
   		this.getDictionaryDeleteButton().show();
   	},
   	
   	
   	//saving data from FORM to DATABASE
   	//calling inserForm(function) ---> this function handle database transaction
   	saveForm : function(){
   		var currentObj = this;

        this.setSourceWordfield(this.getDictionaryForm().getComponent('sourceWordField').getValue());
        this.setPartOfSpeechField(this.getDictionaryForm().getComponent('partOfSpeechField').getValue());  
        this.setInflectionField(this.getDictionaryForm().getComponent('inflectionField').getValue());  
        this.setDisambiguationField(this.getDictionaryForm().getComponent('disambiguationField').getValue());  
        this.setTargetWordField(this.getDictionaryForm().getComponent('targetWordField').getValue());  
        this.setDetailedEntryField(this.getDictionaryForm().getComponent('detailedEntryField').getValue()); 
        this.setNoteField(this.getDictionaryForm().getComponent('noteField').getValue());   
		               	
        var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
        db.transaction(
            function(tx){
        		var querySpeaker = 'INSERT INTO SPEAKER (id, name, birthDate, gender, comments) VALUES (null, "'+ currentObj.getSpeakerName()+'", "'+currentObj.getSpeakerDOB()+'", "'+currentObj.getSpeakerGender()+'","'+currentObj.getSpeakerComment()+'")';
    			tx.executeSql(querySpeaker);
    			
    			var queryCollector = 'INSERT INTO COLLECTOR (id, name, birthDate, gender, comments) VALUES (null, "'+ currentObj.getCollectorName()+'", "'+ currentObj.getCollectorDOB()+'", "'+currentObj.getCollectorGender()+'", "'+currentObj.getCollectorComment()+'")';
    			tx.executeSql(queryCollector);
                       
                console.log('just before select * from speaker...');
    			//query the speaker id
    			tx.executeSql(
                    'SELECT * FROM SPEAKER', 
                    [], 
                    function(tx,results){
                        console.log('Just after...');
                        currentObj.setSpeakerId(results.rows.length);
                        var dictionarySpeakerId = currentObj.getSpeakerId();
                        
                        tx.executeSql(
                            'SELECT * FROM COLLECTOR', 
                            [], 
                            function(tx,results){
                                //query the collector id
                                console.log('in save form...');
                                currentObj.setCollectorId(results.rows.length);
                                var dictionaryCollectorId = currentObj.getCollectorId();
                                console.log('before queryDictionaryTarget');
                                queryDictionaryTarget = 'INSERT INTO DICTIONARYTARGET (id, speakerId, collectorId, targetWord, detailedEntry, audioURL, imageURL, note, savedDate, latitude, longitude, recordingDevice) VALUES(null,'+dictionarySpeakerId+', '+dictionaryCollectorId+', "'+currentObj.getTargetWordField() +'", "'+ currentObj.getDetailedEntryField() +'", "", "", "'+ currentObj.getNoteField() +'", "' + currentObj.getCurrentDate() +'", "' + currentObj.getCurrentLatitude() +'", "' + currentObj.getCurrentLongitude() +'", "' + currentObj.getRecordingDevice() +'")';
                                console.log('after queryDictionaryTarget');
    	
                                tx.executeSql(queryDictionaryTarget);
    					
                                //query the target id
                                tx.executeSql(
                                    'SELECT * FROM DICTIONARYTARGET', 
                                    [], 
                                    function(tx,results){
                                        currentObj.setTargetId(results.rows.length);
    					              
                                        var dictionaryTargetId = currentObj.getTargetId();
    					        
                                        var queryDictionarySource = 'INSERT INTO DICTIONARYSOURCE (id, dictionaryTargetId, sourceWord, partOfSpeech, inflection, disambiguation, targetWord, isEditable) VALUES (null, ' +dictionaryTargetId + ', "' + currentObj.getSourceWordfield() +'", "' + currentObj.getPartOfSpeechField() + '", "' + currentObj.getInflectionField() + '", "' + currentObj.getDisambiguationField() + '",  "' + currentObj.getTargetWordField() + '", 1)';
    					        
                                        tx.executeSql(queryDictionarySource); 
                                    },
                                    errorCB
                                );
                            },
                            function() {
                                console.log('sql error callback');
                            }
                        );
                    },
                    function() {
                        console.log('sql error callback 2');
                    }    
    			);
   
        	}        
        , errorCB);
        
        this.getDictionarySourceListView().getStore().load();
        Ext.getStore("DictionaryTargets").load();
       	Ext.getStore("Collectors").load();
       	Ext.getStore("Speakers").load();
 
   	},
   	
   	// ??
    //
   	updateForm : function(){
   		this.setSourceWordfield(this.getDictionaryForm().getComponent('sourceWordField').getValue());
   		this.setPartOfSpeechField(this.getDictionaryForm().getComponent('partOfSpeechField').getValue());  
   		this.setInflectionField(this.getDictionaryForm().getComponent('inflectionField').getValue());  
   		this.setDisambiguationField(this.getDictionaryForm().getComponent('disambiguationField').getValue());  
   		this.setTargetWordField(this.getDictionaryForm().getComponent('targetWordField').getValue());  
   		this.setDetailedEntryField(this.getDictionaryForm().getComponent('detailedEntryField').getValue()); 
   		this.setNoteField(this.getDictionaryForm().getComponent('noteField').getValue());   
   		
   		var targetId = this.getDictionaryForm().getComponent('targetIdField').getValue(); 
   		var sourceId = this.getDictionaryForm().getComponent('sourceIdField').getValue(); 
   		var speakerId = this.getDictionaryForm().getComponent('speakerIdField').getValue(); 
   		var collectorId = this.getDictionaryForm().getComponent('collectorIdField').getValue(); 

   		
   		var dictionaryTargetStore = Ext.getStore("DictionaryTargets").getById(targetId);
   		var dictionarySourceStore = Ext.getStore("DictionarySources").getById(sourceId);
   		var speakerStore = Ext.getStore("Speakers").getById(speakerId);
   		var collectorStore = Ext.getStore("Collectors").getById(collectorId);
   		
   		dictionarySourceStore.set('sourceWord', this.getSourceWordfield());
   		dictionarySourceStore.set('partOfSpeech', this.getPartOfSpeechField());
   		dictionarySourceStore.set('inflection', this.getInflectionField());
   		dictionarySourceStore.set('disambiguation', this.getDisambiguationField());
   		dictionarySourceStore.set('targetWord', this.getTargetWordField());

   		
   		
        dictionaryTargetStore.set('targetWord', this.getTargetWordField());
        dictionaryTargetStore.set('detailedEntry', this.getDetailedEntryField());
        dictionaryTargetStore.set('note', this.getNoteField());
   		dictionaryTargetStore.set('savedDate', this.getCurrentDate());
   		dictionaryTargetStore.set('latitude', this.getCurrentLatitude());
   		dictionaryTargetStore.set('longitude', this.getCurrentLongitude());
   		dictionaryTargetStore.set('recordingDevice', this.getRecordingDevice());
   		
   		speakerStore.set('name', this.getSpeakerName());
   		speakerStore.set('birthDate', this.getSpeakerDOB());
   	 	speakerStore.set('gender', this.getSpeakerGender());
   	 	speakerStore.set('comments', this.getSpeakerComment());

   		collectorStore.set('name', this.getCollectorName());
   		collectorStore.set('birthDate', this.getCollectorDOB());
   		collectorStore.set('gender', this.getCollectorGender());
   		collectorStore.set('comments', this.getCollectorComment());
   		
   		Ext.getStore("DictionarySources").sync();
   		Ext.getStore("DictionaryTargets").sync();
   		Ext.getStore("Speakers").sync();
   		Ext.getStore("Collectors").sync();
   	},
   	
 
    //play audio when list item is selected
    //
    playAudio: function(theDataView, index, target, record) {
        console.log("PLAY audio");
        // Get associated DictionaryTarget record using dictionaryTargetId foreign key
        var associatedRecord = Ext.getStore("DictionaryTargets").getById( record.get('dictionaryTargetId') );
        var audioURL = Sencha.app.getPersistentFileStoreVar() + "/assets/" + associatedRecord.get('audioURL');
           
        if ( associatedRecord.get('audioURL') ) {
            // Play the audio file at url
            
            var my_media = new Media(
                audioURL,
                // success callback
                function() {
                    console.log("pplayAudio():Audio Success");
                
                },
                // error callback
                function(err) {
                    console.log("pplayAudio():Audio Error: "+err);
                    navigator.notification.alert(msg, null, 'Capture error');
                }
            );
           
            Sencha.app.mediaPtr=my_media;
            my_media.release();  
            Sencha.app.mediaPtr.play();
           
           // Play audio
           //my_media.play();
           // release
           //my_media.release();
           
           // **** Need to release my_media ********//
           // consider creating one for this controller and re-using it. 
           // remove before leaving
        }
    },
    
    
    //fired when back button is pressed on dictionary 
    //
    /*
    backNavigationView: function(){
    	if (this.getDoneDictionaryButton().isHidden() == false){
        	this.getDoneDictionaryButton().hide();
        	this.getAddDictionaryButton().show();
    	}
    },
    */
    
    // Clear dictionary search - fired when clear button pressed
    // 
    clearDictionarySearchFilter: function() {
    	//var sto = this.getDictionarySourceListView().getStore();
    	//sto.clearFilter();
        this.getDictionarySearchField().setValue('');
        this.filterDictionarySearch();
    },
    
    /*
    dictionaryFilter: function(record) {
        console.log("in dictionaryFilter");
        
        return true;
    },
    */
    
           
    // Filter dictionary - fired when value has changed on dictionarySearchField
    // 
    filterDictionarySearch: function() {
        var sto = this.getDictionarySourceListView().getStore();
        var searchString = this.getDictionarySearchField().getValue().toLowerCase();
        var doEnglishSearch = this.getEngDictionaryButtonOn();
        var doIwaidjaSearch = this.getIwaDictionaryButtonOn();
        
        
        console.log('searchString = ' + searchString);
        /*
        var dictFilter = new Ext.util.Filter({
            filterFn: function(item) {
                if (doEnglishSearch) {
                    var srcWord = item.get("sourceWord");
                    //console.log('srcWord = ' + srcWord + ' indexOf=' + srcWord.indexOf(searchString) );
                    // was >-1
                    if ( srcWord.indexOf(searchString)==0 && searchString!='' ) {
                        return true;     
                    } 
                }
                if (doIwaidjaSearch) {
                    var tgtWord = item.get("targetWord");
                    if ( tgtWord.indexOf(searchString)==0 && searchString!='' ) {
                        return true;     
                    } 
                }
            }
        });
        */
           
           
        // clear filter out
        //sto.clearFilter();
        // filter
        //sto.filter(dictFilter);
        //var myFilter = '^' + searchString;
          // console.log('myFilter = ' + myFilter);
        /*   
        // if back key was pressed
        if (this.getLastSearchString().length > searchString.length ) {
           console.log('pop it');
           sto.getFilters().pop();
           sto.load();
        } else {
           var re = new RegExp("\^" + searchString);
           // /^a/
           sto.filter("sourceWord", re );
        }
        
        this.setLastSearchString(searchString); // remember for next time
        */
           
        /*
        var reg = new RegExp("\^" + searchString);
        //var reg = new RegExp('^a', 'i'); 
        var results = Ext.getStore('DictionarySources').queryBy( 
            function(record) { 
                var srcWord = record.get('sourceWord');
                console.log(srcWord);
                if( srcWord=='beach' ) { 
                    return true; 
                } 
            }
        );
        */
         
           
        var resultsArray=new Array();
        var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
        //var filteredStore = this.getDictionarySourceListView()
        
        // if search string is empty, show nothing
        if (searchString=='') {
           Ext.getStore('DictionarySourcesFiltered').setData(resultsArray);
           return;
        }
         
        // Define select statement
        var whereClause = '';
        if ( doEnglishSearch ) {
           whereClause = "sourceWord LIKE '" + searchString + "%' ";
           if ( doIwaidjaSearch ) {
                whereClause +=  ' OR ';
           }
        } 
        if ( doIwaidjaSearch ) {
           whereClause += "targetWord LIKE '" + searchString + "%' ";
        }
           
        db.transaction(
            function(tx) {
                tx.executeSql(
                    "SELECT * FROM DICTIONARYSOURCE WHERE " + whereClause + "ORDER BY sourceWord COLLATE NOCASE", 
                    [], 
                    function (tx2, results) {
                        // the number of rows returned by the select statement
                        console.log("Insert ID = " + results.rows.length);
                              //console.log('results=' + results.rows);
                        var len = results.rows.length;
                        if (len > 25) {
                              len=25;
                        }
                        
                        for (var i=0; i<len; i++){
                             //console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data =  " + results.rows.item(i).data);
                              //console.log( results.rows.item(i) );
                              resultsArray[i]=results.rows.item(i);
                        }
                              console.log('packed array. items = ' + i);
                        Ext.getStore('DictionarySourcesFiltered').setData(resultsArray);
                    }, 
                    function (err) {
                        alert("Error processing SQL 2: "+err.code);    
                    }
                );
            },
            function(err) {
                alert("Error processing SQL 1: "+err.code);
            }
        );
           
        
        // reg.test(srcWord)
           //console.log('results.length = ' + results.getCount() );
          
        /*
        this.getDictionarySourceListView().setStore(
            { 
                model: 'Sencha.model.DictionarySource',
                data: results.getRange(), 
                sorters: [{ property: 'sourceWord' }],
                grouper : function(record) {
                    return record.get('sourceWord').substr(0, 1);
                }                                   
            }
        );
         */  
    },        
    
    
    // Toggle English search on/off
    // mdm 22.04.2012
    //
    toggleEngDictionaryButton: function() {
        // if boolean var for button state is true
        if ( this.getEngDictionaryButtonOn() ) {
            // only toggle off if the other toggle is on ie. can't have both off
            if ( this.getIwaDictionaryButtonOn() ) {
                // toggle button OFF
                this.setEngDictionaryButtonOn(false);
                this.getEngDictionaryButton().addCls('toggleButtonOff');
                // Refilter list now
                this.filterDictionarySearch();
            }
        } else {
            // toggle button ON
            this.setEngDictionaryButtonOn(true);
            // change class
            this.getEngDictionaryButton().removeCls('toggleButtonOff');
            // Refilter list now
            this.filterDictionarySearch();
        }
    },
    
    // Toggle Iwaidja search on/off
    // mdm 22.04.2012
    //
    toggleIwaDictionaryButton: function() {
        // if boolean var for button state is true
        if ( this.getIwaDictionaryButtonOn() ) {
            // only toggle off if the other toggle is on ie. can't have both off
            if ( this.getEngDictionaryButtonOn() ) {
                // toggle button OFF
                this.setIwaDictionaryButtonOn(false);
                this.getIwaDictionaryButton().addCls('toggleButtonOff');
                // Refilter list now
                this.filterDictionarySearch();

            }
        } else {
            // toggle button ON
            this.setIwaDictionaryButtonOn(true);
            // change class
            this.getIwaDictionaryButton().removeCls('toggleButtonOff');
            // Refilter list now
            this.filterDictionarySearch();

        }
    },
    
    // Display meta data form
    //
    showMetadataForm: function(){
   		this.getDictionaryEntryButton().setText('OK');
   		
    	this.getMain().push({
    		xtype: 'dicmetadataformview'			                    
    	});
  
        var d = new Date();
        d.setTime( this.getCurrentDate() );
    	this.getDicMetadaForm().getComponent('dateField').setValue( d.toDateString() );
    	this.getDicMetadaForm().getComponent('latitudeField').setValue(this.getCurrentLatitude());
    	this.getDicMetadaForm().getComponent('longitudeField').setValue(this.getCurrentLongitude());
    	this.getDicMetadaForm().getComponent('recordingDeviceField').setValue(this.getRecordingDevice());
    },
    
    
    showCollectorForm: function() {
    	this.getMain().push({
    		xtype: 'collectorformview'			                    
    	});
    	
    	var tempDate = "";
    	if (this.getCollectorDOB() != ""){
    		tempDate = this.getCollectorDOB().split("/");
    		this.getCollectorNameField().getComponent('collectorDOBField').setValue({day  : tempDate[0], month: tempDate[1], year : tempDate[2]});
    	}
    	
    
    	
    	this.getCollectorNameField().getComponent('collectorNameField').setValue(this.getCollectorName());
    	
    	this.getCollectorGenderField().setGroupValue(this.getCollectorGender());
    	this.getCollectorCommentField().getComponent('collectorCommentField').setValue(this.getCollectorComment());
    	
    	
    },
    
    
    showSpeakerForm: function() {
    	this.getMain().push({
    		xtype: 'speakerformview'			                    
    	});
    	
    	
    	var tempDate = "";
    		if (this.getSpeakerDOB() != ""){
    			tempDate = this.getSpeakerDOB().split("/");
    			this.getSpeakerNameField().getComponent('speakerDOBField').setValue({day  : tempDate[0], month: tempDate[1], year : tempDate[2]});
    		}
    		
    	
    		
    		this.getSpeakerNameField().getComponent('speakerNameField').setValue(this.getSpeakerName());
    		
    		this.getSpeakerGenderField().setGroupValue(this.getSpeakerGender());
    		this.getSpeakerCommentField().getComponent('speakerCommentField').setValue(this.getSpeakerComment());
    	
    	
    
    },
         

    // Add image (located on Add new dictionary entry form
    //
    onAddImageTap: function() {
        console.log("in onAddIimage...");
        
        function onFileSystemFail(evt) {
           console.log(evt.target.error.code);
           var msg = 'An error occurred during capture: ' + evt.target.error.code;
           navigator.notification.alert(msg, null, 'Capture error');
        }
        
        // Move file from temporary storage to persistent storage. Uses PhoneGap File API
        // fst - temporary file system
        // srcFilename - file we want to move located on the temporary file system
        // destDir - sub dir on PERMANENT file system (optional)
        // destFilename - new filename (optional)
        // MDM 17.04.2012
        // 1. Request persistent file system (may need to get a directory here?)
        // 2. Get file from temporary file system using newly encoded filename (ie. ending in m4a)
        // 3. Move file entry from temporary file system to persistent file system
        //
        function fsCopy(fst, srcFilename, destDir, destFilename) {
           console.log("in fsCopy...");
           // Get file we want to copy using Phonegap File API
           fst.getFile (
                srcFilename, 
                {}, 
                // Success callback - get PERSISTENT file system to copy to using Phonegap File API
                function (fileEntry) {
                    window.requestFileSystem (
                        LocalFileSystem.PERSISTENT, 
                        0,
                        // Success callback - get/create sub directory if required else just move file
                        function (fsp) {
                            if ( destDir ) {
                                fsp.root.getDirectory(
                                    destDir,
                                    {create: true},
                                    // Success callback -  move file entry to persistent store 
                                    function(fspDestDir) {
                                        fileEntry.moveTo(
                                            fspDestDir,
                                            destFilename ? destFilename : srcFilename,
                                            function() {
                                                console.log("file saved");
                                            },
                                            onFileSystemFail
                                        );
                                    },
                                    onFileSystemFail
                                );
                            } else {
                                // just move file entry to persistent store root directory
                                fileEntry.moveTo(
                                    fsp.root,
                                    destFilename ? destFilename : srcFilename,
                                    function() {
                                        // need to pass this filename out?
                                        console.log("file saved");
                                    },
                                    onFileSystemFail
                                );              
                            }
                        },
                        onFileSystemFail
                    )
                }, 
                onFileSystemFail
            );
        }
           
           
           
        // Move file from temporary storage to persistent storage. Uses PhoneGap File API
        // MDM 17.04.2012
        // fromPath - path to the file we want to move that is located on the temporary file system
        // destDir - sub directory on permanent file system (optional)
        // destFilename - new name of file (optional - otherwise uses current filename)
        // 1. Request temporary file system 
        //
        function moveFileToPersistentStorage(srcPath, destDir, destFilename) {
           // Connvert path to filename
           var srcFilename = srcPath.replace(/^.*[\\\/]/, '');
           console.log("in moveFileToPersistentStorage...");
           // Request persistent file system (to copy to)
           window.requestFileSystem(
                LocalFileSystem.TEMPORARY, 
                0, 
                function(fst) {
                    fsCopy(fst.root, srcFilename, destDir, destFilename);
                    console.log("calling fsCopy...");
                }, 
                onFileSystemFail
            );
        }
           
           
        // Phonegap device impage capture
        navigator.device.capture.captureImage(
            // success callback
            function(mediaFiles){
                console.log("captured image. Now lets make it permanent...");
                moveFileToPersistentStorage(mediaFiles[0].fullPath,'assets/images',null);
            },
            // fail callback
            function(evt) {
                // Make this an alert
                var msg = 'An error occurred during capture: ' + evt.target.error.code;
                navigator.notification.alert(msg, null, 'Capture error');
            },
            {limit: 1}
        );
    },
           
    // Audio Record
    //
    onAudioRecordTap: function() {
        // Launch device audio recording application
        navigator.device.capture.captureAudio(
            // Capture success callback
            function(mediaFiles){
                console.log ("captured audio");
                // check that an mp4 file with this name doesn't already exist. If it does, delete it
                window.requestFileSystem(
                    LocalFileSystem.TEMPORARY, 
                    0, 
                    // Request file system success callback
                    function(fileSystem){
                        // remove .wav extension and add .mp4 extension - this is the file that the converter will create
                        console.log("just before convertedAudioFilename is created");
                        var convertedAudioFilename = mediaFiles[0].name.replace(/\.[^\.]*$/, '.m4a');
                        console.log ("convertedAudioFilename = " + convertedAudioFilename);
                                                                          
                        // check if the file that the converter will create already exists, and delete it if it does
                        fileSystem.root.getFile(
                            convertedAudioFilename, 
                            { create: false, exclusive: false }, 
                            // FileSystem Success callback (found file) 
                            function success(entry) {
                                // delete file entry
                                console.log("found file, deleting it");
                                // add call backs here?
                                entry.remove();
                                //window.plugins.AudioEncode.encodeAudio(mediaFiles[0].fullPath, "successfulAudioEncode", "failedAudioEncode");
                            },
                            // FileSystem fail callback
                            function fail() {
                                console.log("didn't find file");
                                // if we can't find file, assume it doesn't exist and everything is OK
                                window.plugins.AudioEncode.encodeAudio(mediaFiles[0].fullPath, "successfulAudioEncode", "failedAudioEncode");
                            }
                        );      
                    }, 
                    // Request file system error callback
                    onFileSystemFail
                );
                                                 
            },
            // Capture error callback
            function(error){
                var msg = 'An error occurred during capture: ' + error.code;
                navigator.notification.alert(msg, null, 'Capture error');
            },
            {limit: 1}
        );
    }
});
